
import { ContainerHost } from "../../Container";
import { GroupManService } from "../GroupManService";
import { ModelManService } from "../ModelManService";
import { ISelectManager } from "./ISelectManager";

export class SelectMan implements ISelectManager {

    /**
     * 可选择的模型和dbid
     */
    private passMap: Map<string, number[]> = new Map();
    constructor(private viewer: Sippreep.Viewing.Viewer3D & { toolController: any }) {

    }
    load(): boolean {
        this.addData();
        this.applyPassMap();
        return true;
    }
    unload(): boolean {
        this.unlockAll();
        this.passMap = new Map();
        return true;
    }
    private lockAll(lock: boolean = true) {
        this.viewer.getAllModels().forEach(model => {
            // 讲道理不应该硬编码，但是getRootId函数有小概率出错，猜测是模型数据有问题
            this.viewer.impl.selector.lockSelection([-10000000000], lock, model);
            // this.viewer.impl.selector.lockSelection([model.getRootId()], false, model);
        });
    }
    private unlockAll() {
        this.lockAll(false);
    }
    /**
     * 先把全部锁上不允许选择，再根据数据允许指定部件可以选择
     */
    private applyPassMap() {
        this.lockAll();
        this.passMap.forEach((whiteDbids, modelName) => {
            const model = this.getModel(modelName);
            if (model) {
                this.viewer.impl.selector.lockSelection(whiteDbids, false, model);
            }
        });
    }
    private addData(d?: { groups: { selection: { name: string, dbIds: number[] }[] }[] }) {
        let data: { groups: any[] } = d ?? ContainerHost.Current.Get(GroupManService).getData();
        let groupData: { selection: { dbIds: number[], name: string, url: string }[] }[] = data.groups;
        for (const g of groupData) {
            for (const s of g.selection) {
                this.addPassList(s.name, s.dbIds);
            }
        }
    }
    private getModel(name: string): Sippreep.Viewing.Model {
        return this.viewer.getAllModels().find(m => {
            return ContainerHost.Current.Get(ModelManService).getModelInfo(m).name == name;
        })!;
    }
    private addPassList(modelName: string, whiteDbids: number[]) {
        let tempSet;// = new Set(leaves);
        if (this.passMap.has(modelName)) {
            tempSet = new Set(this.passMap.get(modelName));
        } else {
            tempSet = new Set<number>()
        }
        for (const w of whiteDbids) {
            tempSet.add(w);
        }
        this.passMap.set(modelName, Array.from(tempSet));
    }
}
